#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

// * Copyright (C) 2012  Ruslan Mikhaylenko

long line_count(char *filename) {

        int c;
        long i = 0;
        FILE* fd;

        if ( (fd = fopen(filename, "r")) == NULL) {
                printf("Cant open file - %s\n", filename);
                exit(0);
        }

        while ( (c = fgetc(fd)) != EOF ) {
                if(c == '\n') i++;
        }

        fclose(fd);
        return i;
}

void write_line(char *filename) {

        FILE* fd;
        if ( (fd = fopen(filename, "a")) == NULL) {
                printf("Cant open file - %s\n", filename);
                exit(0);
        }

        for (int i=0; i<10; i++) fprintf(fd, "Another line\n");
        fclose(fd);
}


int main(int argc, char **argv) {

        char first_file[] = "first_file";
        char second_file[] = "second_file";

        long f_count = line_count(first_file);
        long s_count = line_count(second_file);


        while (true) {

                if (f_count > s_count) {
                        write_line(second_file);
                        s_count = line_count(second_file);
                } else {
                        write_line(first_file);
                        f_count = line_count(first_file);
                }
                printf("first file %ld\t second file %ld\r", f_count, s_count);
                fflush(stdout);
                //sleep(1);

        }

        return 0;
}

